package com.bjsxt;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * 创建一个新的XML文档
 */
public class TestDOM4J2 {
    public static void main(String[] args) throws IOException {
        //1.创建一个DocumentFactory对象
        //DocumentFactory  factory = new DocumentFactory();
        //2.使用DocumentFactory创建Document
        //Document doc = factory.createDocument();
        Document doc = DocumentHelper.createDocument();
        doc.addComment("学生信息");
        //3.给Document指定一个根节点students
        Element rootElem = doc.addElement("students");
        //4.给students添加一个子节点student
        Element stuElem = rootElem.addElement("student");

        //5.给student节点添加一个属性节点：id
        stuElem.addAttribute("id","0001");

        //6.给student节点添加子节点：name，age，score
        Element nameElem = stuElem.addElement("name");
        nameElem.setText("王五");
        Element ageElem = stuElem.addElement("age");
        ageElem.setText("25");
        Element scoreElem = stuElem.addElement("score");
        scoreElem.setText("98.5");

        //7.将DOM4j写入一个文件
        OutputFormat format = OutputFormat.createPrettyPrint();//好看的
        Writer write = new FileWriter("java_xml/student3.xml");
        XMLWriter xmlWriter = new XMLWriter(write,format);
        xmlWriter.write(doc);
        xmlWriter.close();






    }
}
